<template>
  <div style="padding: 20px">
    <el-form :model="searchInfo" label-width="100px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="程序编号">
            <el-input v-model="searchInfo.Code" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="程序名称">
            <el-input v-model="searchInfo.Name" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="生产产品">
            <el-input
              v-model="searchInfo.Product"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5">
          <el-form-item label="装夹时间(分)">
            <el-input v-model="searchInfo.ClampLength" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="3" :offset="1">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="middle"
            @click="getList()"
            @keyup.enter="getList()"
            >搜索</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <el-row style="margin-bottom: 10px">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        plain
        size="middle"
        @click="addProgramFun()"
        >新增</el-button
      >
    </el-row>

    <el-table
      border
      :data="tableData"
      style="width: 100%"
      header-row-class-name="tableHead"
      stripe
    >
      <el-table-column
        align="center"
        prop="date"
        type="index"
        label="序号"
        width="50"
      >
      </el-table-column>
      <el-table-column align="center" prop="Code" label="程序编号">
        <template v-slot="{ row }">
          <div
            v-if="row.LastFileID"
            @click="downLoadFile(row.LastFilePath, row)"
            class="deviceTitle"
          >
            {{ row.Code }}
          </div>
          <div v-else>{{ row.Code }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="Name" label="程序名称">
      </el-table-column>
      <el-table-column align="center" prop="Product" label="生产产品">
      </el-table-column>
      <el-table-column align="center" prop="ClampLength" label="装夹时间（分）">
      </el-table-column>
      <el-table-column align="center" prop="LastFileTime" label="最后更新时间">
        <template v-slot="{ row }">
          <div>{{ row.LastFileID ? row.LastFileTime : "-" }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="address"
        label="操作"
        fixed="right"
        width="260"
      >
        <template v-slot="{ row }">
          <div class="opearation">
            <el-button
              icon="el-icon-s-promotion"
              size="small"
              type="info"
              @click="sendProgram(row)"
              >下发</el-button
            >
            <el-button
              icon="el-icon-edit"
              size="small"
              type="primary"
              @click="editProgram(row)"
              >编辑</el-button
            >
            <el-popconfirm
              style="margin-left: 10px"
              :title="`确定删除${row.Name}吗？`"
              @confirm="programDelete(row)"
            >
              <el-button
                slot="reference"
                icon="el-icon-delete"
                size="small"
                type="danger"
                >删除</el-button
              >
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-row type="flex" justify="end">
      <el-pagination
        v-show="total > 0"
        style="margin-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParams.PageIndex"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageParams.PageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>

    <!-- 新增程序 -->
    <el-dialog title="新增" :visible.sync="addDialogVisible" width="50%">
      <el-row>
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <el-col :span="11">
            <el-form-item label="程序编号" prop="Code">
              <el-input v-model="form.Code" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="程序名称" prop="Name">
              <el-input v-model="form.Name" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="生产产品">
              <el-input v-model="form.Product" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="装夹时间（分）">
              <el-input-number
                v-model="form.ClampLength"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="程序文件">
              <input
                class="uploadInput"
                ref="inputUpload"
                type="file"
                v-show="false"
                @change="submitUpload"
              />
              <span v-if="!addChooseFileName" style="margin-right: 20px"
                >未选择文件</span
              >

              <span v-else style="margin-right: 20px">{{
                addChooseFileName
              }}</span>
              <el-button type="primary" size="small" @click="chooseFile()"
                >点击上传</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addProgramSubmit"
          :loading="isUpload"
          >{{ isUpload ? "文件上传中" : "保 存" }}</el-button
        >
      </span>
    </el-dialog>

    <!-- 下发 -->
    <el-dialog title="下发" :visible.sync="sendDialogVisible" width="50%">
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        style="margin-bottom: 10px"
      >
        <el-button
          type="primary"
          size="small"
          @click="sendBtnFun(editInfo.ID)"
          :disabled="!deviceIds.length"
          >一键下发</el-button
        >
        <div>
          <span class="programCodeTitle">程序编号： {{ editInfo.Code }}</span>
          <span style="margin-left: 20px" class="programTime">{{
            editInfo.LastFileTime
          }}</span>
        </div>
      </el-row>
      <el-table
        border
        ref="sendTable"
        stripe
        :data="sendTableData"
        style="width: 100%"
        header-row-class-name="tableHead"
        @selection-change="selectionChange"
      >
        <el-table-column align="center" type="selection" width="50">
        </el-table-column>
        <el-table-column align="center" type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column align="center" prop="Code" label="设备编号">
        </el-table-column>
        <el-table-column align="center" prop="Name" label="设备名称">
        </el-table-column>
        <el-table-column align="center" prop="Model" label="设备型号">
        </el-table-column>
        <el-table-column align="center" prop="Classification" label="设备分类">
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          v-show="total3 > 0"
          style="margin-top: 20px"
          @size-change="handleSizeChange3"
          @current-change="handleCurrentChange3"
          :current-page="sendPage.PageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="sendPage.PageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total3"
        >
        </el-pagination>
      </el-row>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%">
      <el-row>
        <el-form ref="editForm" :model="editInfo" label-width="120px">
          <el-col :span="11">
            <el-form-item label="程序编号">
              <el-input v-model="editInfo.Code" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="程序名称">
              <el-input v-model="editInfo.Name" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="生产产品">
              <el-input
                v-model="editInfo.Product"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="装夹时间（分）">
              <el-input-number
                v-model="editInfo.ClampLength"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="程序文件">
              <input
                class="uploadInput"
                ref="inputUploadEdit"
                type="file"
                v-show="false"
                @change="submitUpload"
              />
              <span v-if="!addChooseFileName" style="margin-right: 20px"
                >未选择文件</span
              >

              <span v-else style="margin-right: 20px">{{
                addChooseFileName
              }}</span>
              <el-button type="primary" size="small" @click="chooseFileEdit()"
                >更新文件</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="historyTitle">历史更迭</div>
      <el-table
        border
        :data="fileTableData"
        style="width: 100%"
        header-row-class-name="tableHead"
        stripe
      >
        <el-table-column align="center" prop="CreateTime" label="上传时间">
        </el-table-column>
        <el-table-column align="center" prop="Size" label="文件大小(KB)">
        </el-table-column>
        <el-table-column align="center" prop="address" label="操作" width="260">
          <template v-slot="{ row }">
            <div class="opearation">
              <el-button
                icon="el-icon-s-promotion"
                size="small"
                type="info"
                @click="sendProgram(editInfo)"
                >下发</el-button
              >
              <el-button
                icon="el-icon-download"
                size="small"
                type="primary"
                @click="downLoadFile(row.Path)"
                >下载</el-button
              >
              <el-popconfirm
                style="margin-left: 10px"
                :title="`确定删除吗？`"
                @confirm="historyDelete(row)"
              >
                <el-button
                  slot="reference"
                  icon="el-icon-delete"
                  size="small"
                  type="danger"
                  >删除</el-button
                >
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          v-show="total > 0"
          style="margin-top: 20px"
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :current-page="filePage.PageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="filePage.PageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        >
        </el-pagination>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editProgramSubmit">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { download } from "@/utils/request";
import {
  GetProgramList,
  UploadFile,
  AddOrUpdateProgram,
  GetProgramFileList,
  DelProgram,
  DelProgramFile,
  GetDeviceList,
  IssuedProgram,
} from "@/api/index";
export default {
  data() {
    return {
      isUpload: false,
      sendPage: {
        PageIndex: 1,
        PageSize: 10,
      },
      pageParams: {
        PageIndex: 1,
        PageSize: 10,
      },
      filePage: {
        PageIndex: 1,
        PageSize: 10,
      },

      total: 0,
      total2: 0,
      total3: 0,
      editDialogVisible: false,
      sendDialogVisible: false,
      addChooseFileName: "",
      isShowSearch: false,
      addDialogVisible: false,
      searchText: "",
      editInfo: {
        Code: undefined,
        Name: undefined,
        Product: undefined,
        ClampLength: undefined,
      },
      form: {
        Code: undefined,
        Name: undefined,
        Product: undefined,
        ClampLength: undefined,
      },
      File: {
        GUID: undefined,
      },

      searchInfo: {
        Code: undefined,
        Name: undefined,
        Product: undefined,
        ClampLength: undefined,
      },
      rules: {
        Code: [{ required: true, message: "请输入程序编号", trigger: "blur" }],
        Name: [{ required: true, message: "请输入程序名称", trigger: "blur" }],
      },
      tableData: [],
      fileTableData: [],
      sendTableData: [],
      deviceIds: [],
    };
  },
  mounted() {
    this.getList();
    this.getDeviceListFun();
  },
  methods: {
    handleSizeChange(val) {
      this.pageParams.PageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageParams.PageIndex = val;
      this.getList();
    },
    handleSizeChange2(val) {
      this.filePage.PageSize = val;
      this.getFileList(this.editInfo);
    },
    handleCurrentChange2(val) {
      this.filePage.PageIndex = val;
      this.getFileList(this.editInfo);
    },
    handleSizeChange3(val) {
      this.sendPage.PageSize = val;
      this.getDeviceListFun();
    },
    handleCurrentChange3(val) {
      this.sendPage.PageIndex = val;
      this.getDeviceListFun();
    },
    async sendBtnFun(id) {
      try {
        let query = {
          ID: id,
          Device_Ids: JSON.stringify(this.deviceIds),
        };
        console.log(query);
        let res = await IssuedProgram(query);
        if (res.Result) {
          this.$message.success("下发成功");
          this.sendDialogVisible = false;
        } else {
          this.$message.error("下发失败" + res.Message);
        }
      } catch (error) {
        console.log(error);
      }
    },

    //获取设备列表
    async getDeviceListFun() {
      try {
        let query = {
          ...this.sendPage,
        };
        let res = await GetDeviceList(query);
        if (res.Result) {
          this.sendTableData = res.Data.List;
          this.total3 = res.Data.Total;
        } else {
          this.$message.error(res.Message);
        }
      } catch (error) {}
    },
    async getList() {
      try {
        let query = {
          ...this.pageParams,
          ...this.searchInfo,
        };
        let res = await GetProgramList(query);
        this.tableData = res.Data.List;
        this.total = res.Data.Total;
      } catch (error) {}
    },
    downLoadFile(path, row) {
      window.open("http://www.infusoft.cn:9801" + path);
    },
    async programDelete(row) {
      let query = {
        ID: row.ID,
      };
      let res = await DelProgram(query);
      if (res.Result) {
        this.$message.success("删除成功");
        this.getList();
      } else {
        this.$message.error("删除失败" + res.Message);
      }
    },
    //获取文件列表
    async getFileList(row) {
      try {
        let query = {
          ...this.filePage,
          ID: row.ID,
        };
        let res = await GetProgramFileList(query);
        if (res.Result) {
          this.fileTableData = res.Data.List;
          this.total2 = res.Data.Total;
          if (this.fileTableData.length > 0) {
            this.addChooseFileName =
              this.fileTableData[0]?.["Name"] +
              this.fileTableData[0]?.["Suffix"];
          } else {
            this.addChooseFileName = "";
          }
        } else {
          this.$message.error(res.Message);
        }
      } catch (error) {}
    },
    //历史删除
    async historyDelete(row) {
      console.log(111);
      try {
        let res = await DelProgramFile({ ID: row.ID });
        if (res.Result) {
          this.$message.success("删除文件成功");
          this.getFileList(this.editInfo);
        } else {
          this.$message.error(res.Message);
        }
      } catch (error) {
        console.log(error);
      }
    },
    //编辑按钮
    async editProgram(row) {
      console.log(row);
      this.editDialogVisible = true;
      this.editInfo = { ...row };
      this.getFileList(row);
    },
    // 下发弹框 选择项改变
    selectionChange(val) {
      this.deviceIds = val.map((item) => item.ID);
      console.log(this.deviceIds);
    },
    //列表下发按钮
    sendProgram(row) {
      this.editInfo = row;
      this.sendDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.sendTable.clearSelection();
      });
    },
    //上传服务器
    async submitUpload(e) {
      const files = e.target.files;
      const rawFile = files[0]; // only use files[0]
      if (!rawFile) return;
      this.addChooseFileName = rawFile.name;
      this.isUpload = true;
      try {
        let formData = new FormData();
        formData.append("file", files[0]);
        let res = await UploadFile(formData);

        if (res.Result) {
          this.File.GUID = res.Data.GUID;
          this.isUpload = false;
          this.$message.success("文件上传成功");
        } else {
          this.isUpload = false;
          this.$message.error("文件上传失败：" + res.Message);
        }
      } catch (error) {
        console.log(error);
      }
      //调用上传接口 获取返回的url
      //   this.upload(rawFile);
    },
    //编辑 更新文件
    chooseFileEdit() {
      this.$refs.inputUploadEdit.click();
    },
    //新增 选择文件
    chooseFile() {
      this.$refs.inputUpload.click();
    },
    //编辑保存
    async editProgramSubmit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          let query = {
            Form: this.editInfo,
            File: this.File,
          };
          try {
            let res = await AddOrUpdateProgram(query);
            if (res.Result) {
              this.$message.success("修改成功");
              this.editDialogVisible = false;
              this.getList();
            } else {
              this.$message.error("修改失败" + res.Message);
            }
          } catch (error) {}
        }
        this.addDialogVisible = false;
      });
    },
    //新增保存
    async addProgramSubmit() {
      let query = {
        Form: this.form,
        File: this.File,
      };
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            let res = await AddOrUpdateProgram(query);
            if (res.Result) {
              this.$message.success("新增成功");
              this.getList();
            } else {
              this.$message.error("新增失败" + res.Message);
            }
          } catch (error) {}
          this.addDialogVisible = false;
        }
      });
    },
    //新增按钮
    addProgramFun() {
      this.addChooseFileName = "";
      this.addDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding-top: 10px;
}
:deep(.el-input-number) {
  width: 100% !important;
  .el-input {
    width: 100% !important;
    .el-input__inner {
      width: 100% !important;
    }
  }
}

.programTime {
  color: rgb(165, 163, 163);
}
.historyTitle {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}
.programCodeTitle {
  font-weight: bold;
  font-size: 14px;
}

.programCode {
  color: $color;
  text-decoration: underline;
  cursor: pointer;
}
:deep(.el-dialog) {
  margin-top: 10vh !important;
}
.opearation {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
}
.deviceTitle {
  color: rgb(41, 102, 233);
  text-decoration: underline;
  cursor: pointer;
}
</style>
